/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice.Instruction;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.WindowManager;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

/**
 * The type Jie shao 0 ability slice.
 *
 * @author Xcl
 * @date 2021 /1/6
 * @package com.xcl.calculator.slice.Instruction
 */
public class JieShao0AbilitySlice extends AbilitySlice implements Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "JieShao0AbilitySlice");
    /**
     * The Click.
     */
    private int click;
    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;

    /**
     * 开始
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_jieshaom);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_jieshaot);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }

            this.findComponentById(ResourceTable.Id_jsshow1).setTouchEventListener(this);
            Text show0 = (Text) this.findComponentById(ResourceTable.Id_jieshao_text_field);
            show0.setText("使用说明" + "\n" + "1.进入主菜单后点击对应功能即可跳转" + "\n" +
                    "2.每一个功能中可以通过左右滑动来切换，且每个模块右滑均可以回到菜单" + "\n" +
                    "3.多功能科学计算上下滑动查看输入所有功能函数" + "\n" +
                    "4.多功能计算器有误差，如需追求高精度，请选择高精度大数计算" + "\n" +
                    "5.高精度大数计算仅支持连续计算" + "\n" +
                    "6.汇率计算需要联网获取当天的汇率，仅供参考" + "\n" +
                    "7.汇率计算快慢与您的网络状况有关，点计算后请耐心等待" + "\n" +
                    "8.进制转换最大支持36进制，大于10进制的数请通过系统自带键盘中输入" + "\n" +
                    "9.多功能科学计算长按每个按钮可以查看每个按钮使用说明" + "\n" +
                    "10.进制转换需要点击右侧按钮后再依次输入数据后，方可计算" + "\n" +
                    "11.时间戳计算会自动根据位数来选择秒/毫秒为基准来求解" + "\n" +
                    "12.时间差计算需要仅时、分、秒支持适配表冠" + "\n" +
                    "13.分布式便签中标题请务必简短，过长标题需要在小窗中滑动查看" + "\n" +
                    "14.分布式便签建议2个设备同时使用，本功能依赖于鸿蒙分布式能力，便签数据不仅支持快速分布式同步，亦支持保存在本地" + "\n" +
                    "15.分布式便签第一页本地信息保存，不会自动销毁，第二页仅用于同步，离开即销毁" + "\n" +
                    "16.所有输入输出框中的数据显示不全时，请左右或上下滑动来查看" + "\n" +
                    "17.关于界面可以联系我、反馈，也可以查看我的最新隐私协议" + "\n" +
                    "18.勾选'不再提示'并关闭本说明后可以再次在'关于-使用说明'中查看");
            Button bt = (Button) this.findComponentById(ResourceTable.Id_jdsfxs_button);
            Checkbox checkbox0 = (Checkbox) this.findComponentById(ResourceTable.Id_checkboxj);
            checkbox0.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
                @Override
                public void onCheckedChanged(AbsButton absButton, boolean b) {
                    // b 为 true 多选按钮选中 , false 取消选中
                    if (b) {
                        bt.setText("我已明白并不再显示");
                        JieShao0AbilitySlice.this.click = 3;
                    } else {
                        bt.setText("我明白了");
                        JieShao0AbilitySlice.this.click = 2;
                    }
                }
            });
            this.findComponentById(ResourceTable.Id_jdsfxs_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    if (JieShao0AbilitySlice.this.click == 3) {
                        JieShao0AbilitySlice.this.ShowDialog("日后可在'关于-使用说明'中查看哦");
                        Preference_RW.ff2_w();
                        //Intent intent1 = new Intent();
                        //JieShao0AbilitySlice.this.present(new CaiDanAbilitySlice(), intent1);
                        //JieShao0AbilitySlice.this.onBackPressed();
                        /*无参--页面跳转开始*/
                        Intent intent1 = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                                .withDeviceId("")
                                .withBundleName(JieShao0AbilitySlice.this.getBundleName())
                                .withAbilityName("com.xcl.calculator.Ability.CaiDanAbility")
                                .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                        intent1.setOperation(operation);// 把operation设置到intent中
                        JieShao0AbilitySlice.this.startAbility(intent1);
                        /*页面跳转结束--无参*/
                        JieShao0AbilitySlice.this.onBackPressed();
                    }
                    //Intent intent1 = new Intent();
                    //JieShao0AbilitySlice.this.present(new CaiDanAbilitySlice(), intent1);
                    //JieShao0AbilitySlice.this.onBackPressed();
                    /*无参--页面跳转开始*/
                    Intent intent1 = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(JieShao0AbilitySlice.this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.CaiDanAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent1.setOperation(operation);// 把operation设置到intent中
                    JieShao0AbilitySlice.this.startAbility(intent1);
                    /*页面跳转结束--无参*/
                    JieShao0AbilitySlice.this.onBackPressed();
                }
            });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 展示数据
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 退出
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return boolean boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog("程序退出成功，感谢您的使用!");
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156)
                    XLog.info(label, "左滑了");
                else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    this.ShowDialog("程序退出成功，感谢您的使用!");
                    this.terminateAbility();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "右滑了");
                } else if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "上滑了");
                else if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                    XLog.info(label, "下滑了");
                else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }
}
